package com.example.csdn.controller;

import com.example.csdn.DTO.LoginDTO;
import com.example.csdn.DTO.RegisterDTO;
import com.example.csdn.pojo.Result;
import com.example.csdn.pojo.User;
import com.example.csdn.service.UserService;
import com.example.csdn.utils.JwtUtil;
import com.example.csdn.utils.Md5Util;
import com.example.csdn.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody @Validated RegisterDTO registerDTO){
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(Md5Util.getMD5String(registerDTO.getPassword()));
        user.setEmail(registerDTO.getEmail());
        User regUser = userService.findByUserName(user.getUsername());
        if (regUser == null){
            //注册
            userService.register(user);
            return Result.success("注册成功");
        }else {
            //已经注册过了
            return Result.error("此用户已存在");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginDTO loginDTO){
        User loginUser = userService.findByUserName(loginDTO.getUsername());
        if (loginUser == null){
            //未注册
            return Result.error("无此用户,请注册");
        }
        if (loginUser.getPassword().equals(Md5Util.getMD5String(loginDTO.getPassword()))){
            //登录
            //生成一个JWT密令,token
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            //存到redis里
            redisTemplate.opsForValue().set(token,token,12, TimeUnit.HOURS);
            //成功
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping
    public Result getUserInfo(){
        Map<String ,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        User user = userService.getUserInfo(userId);
        return Result.success(user);
    }

    @PutMapping
    public Result updateUserInfo(@RequestBody @Validated User user){
        userService.updateUserInfo(user);
        return Result.success("修改成功");
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarURL){
        userService.updateAvatar(avatarURL);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody @Validated Map<String,String> params,@RequestHeader("Authorization")String token){
        //校验参数
        String old_pwd = params.get("old_pwd");
        String new_pwd = params.get("new_pwd");
        String re_pwd = params.get("re_pwd");
        if (!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要参数");
        }
        //判断原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User LoginUser = userService.findByUserName(username);
        if (!LoginUser.getPassword().equals(Md5Util.getMD5String(old_pwd))){
            return Result.error("原密码不对");
        }
        //判断new和re密码是否一致
        if (!new_pwd.equals(re_pwd)){
            return Result.error("两次的密码不一致");
        }

        userService.updatePwd(Md5Util.getMD5String(new_pwd));
        //删除对应的token
        redisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }

}
